
import sys
import os

# print sys.getdefaultencoding()
reload(sys)
sys.setdefaultencoding('utf-8')
# print sys.getdefaultencoding()

abs_file = os.path.abspath(__file__)
root_dir = os.path.dirname(abs_file)
root_dir = os.path.dirname(root_dir)

sys.path.append(os.path.join(root_dir, "3rpart/flask"))
sys.path.append(os.path.join(root_dir, "3rpart/werkzeug"))
sys.path.append(os.path.join(root_dir, "3rpart/jinja"))
sys.path.append(os.path.join(root_dir, "3rpart/markupsafe"))
sys.path.append(os.path.join(root_dir, "3rpart/click"))
sys.path.append(os.path.join(root_dir, "3rpart/itsdangerous"))
sys.path.append(os.path.join(root_dir, "3rpart/flask-paginate"))
sys.path.append(os.path.join(root_dir, "util"))

import pathlist
import storageplist
from flask_paginate import Pagination, get_page_args
from flask import Flask, render_template, g, current_app, request, redirect, url_for
import filelist

app = Flask(__name__)
app.config.from_pyfile('app.cfg')

@app.before_request
def before_request():
	g.pfi = storageplist.PathFileIndex()

@app.teardown_request
def teardown(error):
	if hasattr(g, 'pfi'):
		g.pfi.get_storage().close()


# @app.route("/")
# def index():
# 	return flask.render_template('index.html')

@app.route("/host/list")
def host_list():
	root_uri = request.args.get("root_uri", "")
	link_prefix = request.args.get("link_prefix", "")
	global_link_prefix = request.args.get("global_link_prefix", "")
	host_ctx = []
	host_end = []
	if root_uri:
		root_uri = g.pfi.abs_uri(root_uri)
		dirs, files = g.pfi.list_dirs(root_uri)
		if not link_prefix and global_link_prefix:
			host_ctx.append((-1, g.pfi.parent_uri(root_uri), 
									g.pfi.join_path(global_link_prefix, g.pfi.parent_uri(root_uri))
									))
			host_ctx.append((-1, root_uri, g.pfi.join_path(global_link_prefix, root_uri)))
			for d in dirs:
				uri = g.pfi.join_path(root_uri, d)
				t_link_prefix = g.pfi.join_path(global_link_prefix, uri)
				host_ctx.append((-1, uri, t_link_prefix))
			for f in files:
				uri = g.pfi.join_path(root_uri, f)
				t_link_prefix = g.pfi.join_path(global_link_prefix, uri)
				host_end.append((-1, uri, t_link_prefix))
		else:
			host_ctx.append((-1, g.pfi.parent_uri(root_uri), link_prefix))
			host_ctx.append((-1, root_uri, link_prefix))
			for d in dirs:
				host_ctx.append((-1, g.pfi.join_path(root_uri, d), link_prefix))
			for f in files:
				host_end.append((-1, g.pfi.join_path(root_uri, f), link_prefix))
	else:
		host_ctx = g.pfi.get_storage().get_hosts()

	return render_template("host_list.html", 
							host_ctx = host_ctx,
							host_end = host_end,
							root_uri=root_uri,
							link_prefix=link_prefix,
							global_link_prefix=global_link_prefix)

@app.route("/host/add")
def host_add():
	root_uri = request.args.get("root_uri")
	link_prefix = request.args.get("link_prefix")
	if not link_prefix:
		return "link_prefix not allow empty"
	g.pfi.get_storage().add_host(root_uri, link_prefix)
	return redirect(url_for('host_list'))

@app.route("/host/del")
def host_del():
	host_id = request.args.get("id")
	g.pfi.get_storage().host_del(host_id)
	return redirect(url_for('host_list'))

@app.route("/path/scan")
def path_scan():
	stop = request.args.get("stop", False)
	if stop != False:
		g.pfi.stop_scan()
		return "stop scan finish"
	root_uris = []
	link_prefixs = []
	root_uri = request.args.get("root_uri")
	link_prefix = request.args.get("link_prefix")
	if root_uri != None:
		root_uris.append(root_uri)		
		link_prefixs.append(link_prefix)
	else:
		for host in g.pfi.get_storage().get_hosts():
			root_uris.append(host[1])
			link_prefixs.append(host[2])
	max_depth = request.args.get("maxdepth", 10)
	max_depth = int(max_depth)
	g.pfi.gen_index(root_uris, link_prefixs, backround=True, max_depth=max_depth)
	return redirect(url_for("path_list"))

@app.route("/path/del")
def path_empty():
	link_prefix = request.args.get("link_prefix")
	if link_prefix:
		g.pfi.get_storage().empty(link_prefix)
	else:
		g.pfi.get_storage().empty_all()
	return redirect(url_for("host_list"))

@app.route("/path/list")
def path_list():
	assert request.method == "GET"
	link = request.args.get("link", "")
	page, per_page, offset = get_page_args()
	total = g.pfi.get_storage().get_total_count(link=link)
	paths = g.pfi.get_storage().query(page_offset=offset, 
									page_per_page=per_page,
									link=link)

	pagination = get_pagination(page=page,
								per_page=per_page,
								total=total,
								record_name='path_list',
								format_total=True,
								format_number=True)

	return render_template('list.html', paths=paths,
										page=page,
										per_page=per_page,
										pagination=pagination,
										query_link=link,
										dirname=os.path.dirname,
										hostname=request.host.split(":")[0])

@app.route("/")
def init():
	g.pfi.init()
	return redirect(url_for("path_list"))

def get_css_framework():
	return current_app.config.get('CSS_FRAMEWORK', 'bootstrap4')


def get_link_size():
	return current_app.config.get('LINK_SIZE', 'sm')


def get_alignment():
	return current_app.config.get('LINK_ALIGNMENT', '')


def show_single_page_or_not():
	return current_app.config.get('SHOW_SINGLE_PAGE', False)


def get_pagination(**kwargs):
	kwargs.setdefault('record_name', 'records')
	return Pagination(css_framework=get_css_framework(),
						link_size=get_link_size(),
						alignment=get_alignment(),
						show_single_page=show_single_page_or_not(),
						**kwargs
						)

if __name__ == '__main__':
	# app.run(debug=True)
	app.run(host="0.0.0.0")



